package com.music.Utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 歌词处理类
 * 
 * @author yangyong
 * 
 */
public class LrcProcessorUtil {
	public String songName = null;
	public String singer = null;
	public String author = null;
	public String details = null;
	public ArrayList<Object> lists = null;

	public ArrayList<Object> process(String text) {
		// 生成两个个队列对象，用于存放歌词播放时间和歌词内容，一个HashMap对象用于存放歌的前期描述内容
		Queue<Long> timeMills = new LinkedList<Long>();
		Queue<String> messages = new LinkedList<String>();
		HashMap<String, String> ahead = new HashMap<String, String>();
		HashMap lrcMap = new HashMap();

		InputStream inputStream = new ByteArrayInputStream(text.getBytes());

		// 生成一个列表对象，用于存放两个队列
		lists = new ArrayList<Object>();

		/*
		 * //用字节数组读取输入流，解决汉字乱码问题 BufferedInputStream bis=new
		 * BufferedInputStream(inputStream); byte [] buf=new byte[1024*4];
		 * bis.read(buf); String temp=new String(buf,"UTF-8");
		 */

		// 将输入流存入BufferedReader 对象中
		InputStreamReader inputReader = null;
		try {
			inputReader = new InputStreamReader(inputStream, "utf-8");

		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		BufferedReader bufferedReader = new BufferedReader(inputReader);

		String line = null;
		int timeStrLength = 0;
		int i = 0;
		// 生成一个正则表达式
		Pattern p = Pattern.compile("(?<=\\[).*?(?=\\])");

		String content = null;
		boolean b = true;
		long lastTimeMill = 0;
		try {
			while ((line = bufferedReader.readLine()) != null) {
				// 每一行读取的输入信息与正则表达式相匹配
				int num = 0;
				while (timeStrLength * num + 1 <= line.length()) {
					String subLine = line.substring(timeStrLength * num,
							line.length());
					num++; // 一行中有可能包含多条时间信息，对应同一句歌词
					Matcher m = p.matcher(subLine);
					if (m.find()) {

						String timeStr = m.group();
						timeStrLength = timeStr.length() + 2;
						String[] s = timeStr.substring(0, timeStr.length())
								.split("\\:|\\.");
						if (s[0].equals("ti")) {
							if (s.length > 1)
								ahead.put("TI", s[1]);
						} else if (s[0].equals("ar")) {
							if (s.length > 1)
								ahead.put("AR", s[1]);
						} else if (s[0].equals("by")) {
							if (s.length > 1)
								ahead.put("BY", s[1]);
						} else if (s[0].equals("al")) {
							if (s.length > 1)
								ahead.put("AL", s[1]);
						} else {
							// 将时间点字串转化为长整型
							Long timeMill = time2Long(s);
							if (timeMill != -1) {
								i++;
								lrcMap = new HashMap();
								// 将得到的时间点压入时间队列中，注意：如果没有限制容量的压入队列，用队列的offer()方法压入
								lrcMap.put("timeMill", timeMill);

								String msg = line.substring(
										line.lastIndexOf("]") + 1,
										line.length());
								content = msg.trim() + "\n";
								lrcMap.put("content", content);
								lists.add(lrcMap);
							}
						}
					} else {
						if (num != 0) {
							break;
						} else {// 如果该行中没有找到匹配字串，将整行都加入到上一次的歌词字串中
							content = content + line;
							// 将歌messages.add(content);词字串添加到歌词队列中，
							// 注意：如果限制容量的压入队列，用队列的add()方法压入

							lrcMap.put("content",
									((String) lrcMap.get("content")) + content);
							lists.remove(i - 1);
							lists.add(lrcMap);
						}
					}
				}
			}
			bufferedReader.close();
			inputReader.close();

		} catch (IOException e) {

			e.printStackTrace();
		}
		// 对lists按时间由小到大进行排序
		TimeCompare timeCompare = new TimeCompare();
		Collections.sort(lists, timeCompare);

		return lists;
	}

	// 将时间串转化为时间数
	public Long time2Long(String[] s) {
		if (s.length < 2) {
			return -1L;
		} else if (s.length == 2) {
			try {
				int min = Integer.parseInt(s[0]);
				int sec = Integer.parseInt(s[1]);
				if (min < 0 || sec < 0 || sec >= 60) {
					throw new RuntimeException("数字不合法!");
				}
				return (min * 60 + sec) * 1000L;
			} catch (Exception exe) {
				return -1L;
			}
		} else if (s.length == 3) {
			int min = Integer.parseInt(s[0]);
			int sec = Integer.parseInt(s[1]);
			int mill = Integer.parseInt(s[2]);
			return (min * 60 + sec) * 1000L + mill * 10L;
		} else {
			return -1L;
		}
	}

	/*
	 * 对时间比较大小
	 */
	public class TimeCompare implements Comparator {

		public int compare(Object object1, Object object2) {
			HashMap map1 = (HashMap) object1;
			HashMap map2 = (HashMap) object2;
			Long time1 = (Long) map1.get("timeMill");
			Long time2 = (Long) map2.get("timeMill");
			int result = time1.compareTo(time2);
			return result;
		}
	}

}